package com.dynamic.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.dynamic.mybatis.core.datasource.DynamicMultipleDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2021/3/26 19:01
 */
@Configuration
public class MultipleDataSourceConfig {

    @Bean("assistDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.assist")
    public DruidDataSource assist() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean("mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DruidDataSource mysql() {
        return DruidDataSourceBuilder.create().build();
    }


    @Primary
    @Bean(name = "routingDataSource")
    public DynamicMultipleDataSource routingDataSource(@Autowired @Qualifier("assistDataSource") DataSource assistDataSource,
                                                       @Autowired @Qualifier("mysqlDataSource") DataSource mysqlDataSource) {
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("assist",assistDataSource);
        dataSourceMap.put("mysql",mysqlDataSource);
        return new DynamicMultipleDataSource(assistDataSource,dataSourceMap);
    }
}